package com.ruoyi.web.controller.report;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.report.domain.CommunityPolicy;
import com.ruoyi.report.domain.DemoBO;
import com.ruoyi.report.service.ICommunityPolicyService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.report.domain.CommunityReporting;
import com.ruoyi.report.service.ICommunityReportingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 档案Controller
 *
 * @author mac
 * @date 2023-02-11
 */
@RestController
@RequestMapping("/report/reporting")
public class CommunityReportingController extends BaseController {

    @Autowired
    private ICommunityReportingService communityReportingService;

    @Autowired
    private ICommunityPolicyService communityPolicyService;

    @PostMapping("/typeList")
    public AjaxResult typeList(CommunityReporting communityReporting) {

        List<CommunityReporting> list = getList(communityReporting);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.success(null);
        }
        Map<String, String> map = new HashMap<>();

        for (CommunityReporting notice : list) {
            map.put(notice.getXueQi(), notice.getsGao());
        }

        Map<String, List<String>> data = getData(map);
        return AjaxResult.success(data);
    }

    @PostMapping("/borrowList")
    public AjaxResult borrowList(CommunityReporting communityReporting) {

        List<CommunityReporting> list = getList(communityReporting);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.success(null);
        }
        Map<String, String> map = new HashMap<>();

        for (CommunityReporting notice : list) {
            map.put(notice.getXueQi(), notice.getWeight());
        }

        Map<String, List<String>> data = getData(map);
        return AjaxResult.success(data);

    }

    @PostMapping("/bmiList")
    public AjaxResult bmiList(CommunityReporting communityReporting) {
        List<CommunityReporting> list = getList(communityReporting);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.success(null);
        }
        Map<String, String> map = new HashMap<>();

        for (CommunityReporting reporting : list) {
            double sGao = Double.parseDouble(reporting.getsGao()) / 100;
            double weight = Double.parseDouble(reporting.getWeight());
            map.put(reporting.getXueQi(),
                    String.valueOf(weight / (sGao * sGao)).substring(0, 2)
            );
        }

        Map<String, List<String>> data = getData(map);
        return AjaxResult.success(data);

    }

    private Map<String, List<String>> getData(Map<String, String> map) {
        List<String> keys = new ArrayList<>();
        List<String> values = new ArrayList<>();
        map.forEach((key, value) -> {
            keys.add(key);
            values.add(String.valueOf(value));
        });

        Map<String, List<String>> data = new HashMap<>();
        data.put("key", keys);
        data.put("value", values);
        return data;
    }

    private List<CommunityReporting> getList(CommunityReporting communityReporting) {
        List<CommunityReporting> list = communityReportingService
                .selectCommunityReportingList(communityReporting);
        if (StringUtils.isEmpty(communityReporting.getUserName())) {
            return null;
        }
        list = list.stream().sorted(Comparator.comparing(CommunityReporting::getXueQi).reversed())
                .collect(Collectors.toList());

        return list;
    }


    /**
     * 查询档案列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CommunityReporting communityReporting) {
        startPage();
        List<CommunityReporting> list = communityReportingService
                .selectCommunityReportingList(communityReporting);
        return getDataTable(list);
    }

    @GetMapping("/worldData")
    public DemoBO worldData(CommunityReporting communityReporting) {
        Long id = communityReporting.getId();
        CommunityReporting entity = communityReportingService.selectCommunityReportingById(id);
        if (Objects.isNull(entity)) {
            return null;
        }
        DemoBO demoBO = new DemoBO();
        BeanUtils.copyProperties(entity, demoBO);
        double sGao = Double.parseDouble(entity.getsGao()) / 100;
        double tZhong = Double.parseDouble(entity.getWeight());
        String bmi = String.valueOf(tZhong / (sGao * sGao)).substring(0, 2);
        demoBO.setBmi(Double.valueOf(bmi));

        CommunityPolicy communityPolicy = new CommunityPolicy();
        communityPolicy.setUsername(demoBO.getUserName());
        List<CommunityPolicy> communityPolicies = communityPolicyService.selectCommunityPolicyList(communityPolicy);
        Set<String> collect = communityPolicies.stream().map(CommunityPolicy::getContent).collect(Collectors.toSet());
        StringBuilder idea = new StringBuilder();
        for (String s : collect) {
            idea.append(s);
        }
        demoBO.setIdea(idea.toString());

        return demoBO;
    }

    /**
     * 导出档案列表
     */
    @PreAuthorize("@ss.hasPermi('report:reporting:export')")
    @Log(title = "档案", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommunityReporting communityReporting) {
        List<CommunityReporting> list = communityReportingService
                .selectCommunityReportingList(communityReporting);
        ExcelUtil<CommunityReporting> util = new ExcelUtil<CommunityReporting>(
                CommunityReporting.class);
        util.exportExcel(response, list, "档案数据");
    }

    /**
     * 获取档案详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(communityReportingService.selectCommunityReportingById(id));
    }

    /**
     * 新增档案
     */
    @Log(title = "档案", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommunityReporting communityReporting) {
        CommunityReporting communityReporting1 = communityReportingService
                .selectCommunityReportingByNameAndMemo(getUsername(), communityReporting.getXueQi());

        if (!Objects.isNull(communityReporting1)) {
            throw new RuntimeException("年度学期请勿重复提交");
        }

        CommunityReporting communityReporting2 = new CommunityReporting();
        communityReporting2.setUserName(getUsername());
        List<CommunityReporting> communityReportings = communityReportingService
                .selectCommunityReportingList(communityReporting2);
        if (!CollectionUtils.isEmpty(communityReportings) && communityReportings.size() == 8) {
            throw new RuntimeException("最大学期数不能超过8个学期");
        }

        communityReporting.setCreateAt(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        return toAjax(communityReportingService.insertCommunityReporting(communityReporting));
    }

    /**
     * 修改档案
     */
    @Log(title = "档案", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommunityReporting communityReporting) {
        return toAjax(communityReportingService.updateCommunityReporting(communityReporting));
    }

    /**
     * 删除档案
     */
//    @PreAuthorize("@ss.hasPermi('report:reporting:remove')")
    @Log(title = "档案", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(communityReportingService.deleteCommunityReportingByIds(ids));
    }
}
